package com.teach.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.teach.Const;
import com.teach.service.LjService;
import com.teach.service.impl.LjServiceImpl;
import com.teach.vo.LoginUser;

@WebServlet("/login.let")
public class LoginServlet extends HttpServlet{

	private LjService ljService = new LjServiceImpl();
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("name="+name);
		System.out.println("password="+password);
		
		try {
			String code = request.getParameter("codeName");
			Const.codeVerify(request.getSession(), code);
			
			LoginUser user = ljService.login(name, password);
			System.out.println(user);
			request.getSession().setAttribute(Const.LOGIN_USER_SESSION_NAME, user);
			request.setAttribute("msg", "登录成功！");
			
			//如果是管理员，就跳到管理员页面，如果不是管理员，就跳到首页
			response.sendRedirect(request.getContextPath()+"/");
			return ;
		}catch(Exception e) {
			e.printStackTrace();//记调试日志
			request.setAttribute("error", "添加用户失败"+e.getMessage());
		}
		
		request.getRequestDispatcher("/msg.jsp").forward(request, response);
	}
}
